var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
var __reExport = (target, module2, desc) => {
  if (module2 && typeof module2 === "object" || typeof module2 === "function") {
    for (let key of __getOwnPropNames(module2))
      if (!__hasOwnProp.call(target, key) && key !== "default")
        __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
  }
  return target;
};
var __toModule = (module2) => {
  return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
};

// app.ts
var events = __toModule(require("events"));
var net = __toModule(require("net"));
var channel = new events.EventEmitter();
var clients = {};
var subscriptions = {};
channel.setMaxListeners(10);
channel.on("join", function(id, client) {
  console.log(`${id} join the chatroom`);
  const welcome = `
        Welcome!
            Guests online: ${channel.listeners("broadcast").length}
    `;
  client.write(`${welcome}
`);
  clients[id] = client;
  subscriptions[id] = (senderId, message) => {
    if (id !== senderId) {
      clients[id].write(message);
    }
  };
  channel.on("broadcast", subscriptions[id]);
  channel.on("leave", function(leaveId) {
    if (id !== leaveId)
      return;
    channel.removeListener("broadcast", subscriptions[id]);
    channel.emit("broadcast", id, `${id} has left the chatroom.
`);
    console.log(`${id} left the chatroom`);
  });
});
channel.on("shutdown", () => {
  channel.emit("broadcast", "", "The server has shut down.\n");
  channel.removeAllListeners("broadcast");
});
var server = net.createServer((client) => {
  const id = `${client.remoteAddress}:${client.remotePort}`;
  channel.emit("join", id, client);
  client.on("data", (data) => {
    const str = data.toString();
    if (str === "shutdown\r\n") {
      channel.emit("shutdown");
    }
    channel.emit("broadcast", id, str);
  });
  client.on("close", () => {
    channel.emit("leave", id);
  });
});
server.listen(8888);
console.log("server running on 127.0.0.1:8888");
